import { client } from '../../request/index.js'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

Page({
  data: {
    ip: getApp().globalData.ip,
    imgIp: getApp().globalData.imgIp,
    inputValue: '',
    pageNum: 1,
    isLogin: false,
    hasNextPage: true,
    info: [],
    sessionid: null, //登录判断
    navbarInitTop: 0, //导航栏初始化距顶部的距离
    isFixedTop: false, //是否固定顶部
    widthChange: false,
    isResEmptyHidden: true,
    searchEntered: '',
    guide3: false, // 显示引导3
  },

  itemClick: function (item) {
    let id = item.currentTarget.dataset.id
    console.log(id)
    wx.navigateTo({
      url: '../../pages/dt_xq/dt_xq?id=' + id,
    })
  },

  dtRec: function (e) {
    if (getApp().globalData.sessionid === '') {
      getApp().globalData.showLoginDialog = true
      Dialog.alert({
        title: '检测到尚未登录',
        message: '将为您跳转到其它界面进行登录',
      }).then(() => {
        wx.switchTab({
          url: '../../pages/my/my',
        })
      })
    } else {
      wx.navigateTo({
        url: '../../pages/dt_rec/dt_rec',
      })
    }
  },
  // 查询贫困户列表
  async findList(pageNum, pageSize, reload) {
    let that = this
    if (reload === true) {
      that.setData({
        info: [],
      })
    }
    const getData = await client({
      url: '/poor-man-info/public/list',
      data: {
        pageNum: pageNum,
        pageSize: pageSize,
      },
    })
    console.log('贫困户信息：', getData)
    that.setData({
      hasNextPage: getData.data.data.hasNextPage,
    })
    let newList = []
    for (let item in getData.data.data.list) {
      let value = getData.data.data.list[item]
      let newInfo = {}
      newInfo['animation'] = ''
      newInfo['width'] = '100%'
      newInfo['type'] = '贫困户'
      newInfo['content'] = value.content
      newInfo['img'] =
        getApp().globalData.ip + '/' + value.coverPicUrl.split(' ')[0]
      newInfo['currentMoney'] = value.needMoney - value.currentMoney
      newInfo['id'] = value.id
      newInfo['city'] = value.location
      newInfo['needMoney'] = value.needMoney
      newInfo['title'] = value.title
      newInfo['userId'] = value.userId
      newList.push(newInfo)
    }
    that.setData({
      info: that.data.info.concat(newList),
    })
    for (var item in that.data.info) {
      var width =
        (100 * that.data.info[item]['currentMoney']) /
          that.data.info[item]['needMoney'] +
        '%'
      var animation = 'info[' + item + '].animation'
      var _animation = wx.createAnimation({
        duration: 700,
      })
      _animation.width(width).step()
      that.setData({
        [animation]: _animation.export(),
      })
    }
  },
  // 获取输入关键字
  handleSearchInput(e) {
    let inputValue = e.detail.value
    this.setData({
      inputValue,
    })
    if (inputValue === '') {
      this.handleReset()
    }
  },
  // 回车搜索
  async handleSearch() {
    let that = this
    if (that.data.inputValue === '') {
      Toast.fail('输入不能为空')
      return
    }
    const getData = await client({
      url: '/poor-man-info/public/list',
      data: {
        pageNum: 1,
        pageSize: 50,
        key: that.data.inputValue,
      },
    })
    console.log('搜索结果：', getData)
    if (getData.data.data.list.length === 0) {
      this.setData({
        isResEmptyHidden: false,
      })
    } else {
      Toast.success('搜索成功')
      let newList = []
      for (let item in getData.data.data.list) {
        let value = getData.data.data.list[item]
        let newInfo = {}
        newInfo['animation'] = ''
        newInfo['width'] = '100%'
        newInfo['type'] = '贫困户'
        newInfo['content'] = value.content
        newInfo['img'] =
          getApp().globalData.ip + '/' + value.coverPicUrl.split(' ')[0]
        newInfo['currentMoney'] = value.needMoney - value.currentMoney
        newInfo['id'] = value.id
        newInfo['city'] = value.location
        newInfo['needMoney'] = value.needMoney
        newInfo['title'] = value.title
        newInfo['userId'] = value.userId
        newList.push(newInfo)
      }
      that.setData({
        info: newList,
        searchEntered: that.data.inputValue,
      })
      for (var item in that.data.info) {
        // 设置进度条宽度
        var width =
          (100 * that.data.info[item]['currentMoney']) /
            that.data.info[item]['needMoney'] +
          '%'
        var animation = 'info[' + item + '].animation'
        var _animation = wx.createAnimation({
          //创建动画
          duration: 200,
        })
        _animation.width(width).step()
        that.setData({
          [animation]: _animation.export(),
        })
      }
    }
  },

  handleReset() {
    this.setData({
      isResEmptyHidden: true,
      inputValue: '',
      searchEntered: '',
    })
    this.findList(1, 5, true)
  },
  // 引导3知道了
  guideDt1_cancel() {
    wx.setStorage({
      key: 'dtGuideOpen',
      data: 'known',
    })
    this.setData({
      guide3: false,
    })
    wx.setStorage({
      key: 'dtXqGuideOpen',
      data: true,
    })
    let info = this.data.info
    let id = info[0].id
    wx.navigateTo({
      url: '/pages/dt_xq/dt_xq?id=' + id,
    })
  },
  // 引导3跳过
  guideDt1_skip1() {
    wx.setStorage({
      key: 'dtGuideOpen',
      data: 'known',
    })
    this.setData({
      guide3: false,
    })
    wx.setStorage({
      key: 'dtXqGuideOpen',
      data: true,
    })
  },

  onLoad: function (options) {
    if (getApp().globalData.sessionid !== '') {
      this.setData({
        isLogin: true,
        inputValue: '',
        searchEntered: '',
      })
    }
  },

  onShow: function () {
    let that = this
    if (that.data.navbarInitTop == 0) {
      //获取节点距离顶部的距离
      wx.createSelectorQuery()
        .select('#Topbar')
        .boundingClientRect(function (rect) {
          if (rect && rect.top > 0) {
            let navbarInitTop = parseInt(rect.top)
            that.setData({
              navbarInitTop: navbarInitTop,
            })
          }
        })
        .exec()
    }
    if (getApp().globalData.sessionid !== '') {
      this.setData({
        isLogin: true,
        inputValue: '',
        searchEntered: '',
      })
      this.findList(1, 5, true)
    }
    // 判断是否显示过引导3
    let thirdOpen = wx.getStorageSync('dtGuideOpen')
    if (thirdOpen == 'unknown') {
      this.setData({
        guide3: true,
      })
    } else {
      this.setData({
        guide3: false,
      })
    }
  },

  onPageScroll: function (e) {
    var that = this
    var scrollTop = parseInt(e.scrollTop) //滚动条距离顶部高度
    //判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
    var isSatisfy = scrollTop >= that.data.navbarInitTop ? true : false
    //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
    if (that.data.isFixedTop === isSatisfy) {
      return false
    }
    that.setData({
      isFixedTop: isSatisfy,
      widthChange: isSatisfy,
    })
  },

  onPullDownRefresh: function () {
    this.onLoad()
    this.onShow()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  onReachBottom: function () {
    let inputValue = this.data.inputValue
    let searchEntered = this.data.searchEntered
    if (inputValue === '' && searchEntered === '') {
      this.setData({
        pageNum: this.data.pageNum + 1,
      })
      this.findList(this.data.pageNum, 5, false)
    }
  },
})
